<script setup lang="ts">
import { computed, ref } from 'vue';
import pinyin from 'pinyin';
import type { IPinyinStyle } from 'pinyin/lib/types/declare';

const text = ref('汉字转拼音');

const styleVal = ref<IPinyinStyle>('NORMAL'); // 对应 pinyin.STYLE_XXX
const enableSegment = ref(true); // 分词（降低多音字错误）

const result = computed<string[]>(() => {
    if (!text.value.trim()) return [];

    // 不i是中文的 全部替换 为 ''
    const res = pinyin(text.value, {
        segment: enableSegment.value,
        heteronym: false, // 是否启用多音字模式，默认不启用
        style: styleVal.value,
    });

    return res.map((item) => item[0]!);
});
</script>
<template>
    <section>
        <h2>汉字转拼音</h2>
        <textarea
            v-model="text"
            rows="4"
            placeholder="请输入汉字（自动过滤非汉字）"
        />

        <div class="options">
            <label>
                风格
                <select v-model="styleVal">
                    <option value="NORMAL">无声调</option>
                    <option value="TONE">带声调符号</option>
                    <option value="TONE2">数字标声调</option>
                    <option value="FIRST_LETTER">首字母</option>
                </select>
            </label>

            <label>
                <input type="checkbox" v-model="enableSegment" />
                分词（降低多音字错误）
            </label>
        </div>

        <p>
            <!-- replace(/[^\p{L}\p{N}]/gu, '') 去除标点符号 -->
            <span
                v-for="(zi, index) of text"
                :key="zi"
                :data-pinyin="result[index]"
                >{{ zi }}</span
            >
        </p>
    </section>
</template>

<style scoped lang="scss">
section {
    textarea {
        resize: none;
        border: none;
        outline: none;
        border-radius: 10px;
        padding: 10px;
    }

    .options {
        margin: 8px 0;
    }

    label {
        margin-right: 16px;
    }

    p {
        span {
            position: relative;
            font-size: 15px;
            padding: 10px;
            display: inline-block;

            &::after {
                content: attr(data-pinyin);
                display: block;
                position: absolute;
                left: 50%;
                top: -5px;
                color: #ff1818;
                font-size: 12px;
                transform: translateX(-50%);
            }
        }
    }
}
</style>
